import logging
import os
from datetime import datetime, timedelta

class CustomLogger:
    def __init__(self, name, days_to_keep=7):
        self.name = name
        self.log_dir = self.get_log_dir()
        self.days_to_keep = days_to_keep
        self.logger = logging.getLogger(name)
        self.setup()

    def setup(self):
        # 确保日志目录存在
        if not os.path.exists(self.log_dir):
            os.makedirs(self.log_dir)

        # 日志文件名格式：xxx-日期.log
        today = datetime.now().strftime('%Y-%m-%d')
        log_filename = f"{self.name}_{today}.log"
        log_filepath = os.path.join(self.log_dir, log_filename)

        # 删除超过指定天数的日志文件
        self.delete_old_logs(today)

        # 设置日志级别和格式
        self.logger.setLevel(logging.DEBUG)
        handler = logging.FileHandler(log_filepath, encoding="utf-8")
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)

    def delete_old_logs(self, today):
        # 计算需要保留的日志文件的日期
        cutoff_date = (datetime.now() - timedelta(days=self.days_to_keep)).strftime('%Y-%m-%d')
        for filename in os.listdir(self.log_dir):
            if filename.startswith(self.name) and filename.endswith('.log'):
                # 获取日志文件的日期部分
                date_part = filename.replace(self.name + "_", "").replace(".log","")
                if date_part < cutoff_date:
                    # 删除旧的日志文件
                    os.remove(os.path.join(self.log_dir, filename))

    def get_logger(self):
        return self.logger

    def get_log_dir(self):
        # 获取当前文件（main.py）的目录路径
        current_dir = os.path.dirname(os.path.abspath(__file__))

        # 获取上一级目录的路径（即project_root）
        parent_dir = os.path.dirname(current_dir)

        # 构建logs目录的路径
        log_dir = os.path.join(parent_dir, 'logs')

        return log_dir

# 使用CustomLogger
# if __name__ == "__main__":
#     logger = CustomLogger('shangh')
#     logger.get_logger().info('This is an info message')
#     logger.get_logger().debug('This is a debug message')